package com.example.viewmodeltemplate;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

public class MyViewModel extends AndroidViewModel {

    private static final String SHP_NAME = "MY_DATA";

    private static final String NUMBER = "number";
    private MutableLiveData<Integer> mNumber;

    public MyViewModel(@NonNull Application application) {
        super(application);
    }

    public MutableLiveData<Integer> getmNumber() {
        if (mNumber == null) {
            mNumber = new MutableLiveData<>();
            mNumber.setValue(0);
        }
        return mNumber;
    }

    public void load() {
        SharedPreferences shp = getApplication().getSharedPreferences(SHP_NAME, Context.MODE_PRIVATE);
        int number = shp.getInt(NUMBER, 0);
        getmNumber().setValue(number);
    }

    public void save() {
        SharedPreferences shp = getApplication().getSharedPreferences(SHP_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = shp.edit();
        editor.putInt(NUMBER, getmNumber().getValue());
        editor.apply();
    }

    public void add(int x) {
        getmNumber().setValue(getmNumber().getValue() + x);
    }


}
